#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include <unistd.h>
#include<signal.h>
#include<sys/wait.h>



//SIGCHLD信号处理函数
void waitchild(int signo)
{
	pid_t wpid = waitpid(-1,NULL,WNOHANG);
	if(wpid>0)
	{
		printf("child is quit,wpid==[%d]\n",wpid);
	}
	if(wpid==0)
	{
		printf("child is living,wpid==[%d]\n",wpid);
	}
	if(wpid==-1)
	{
		printf("no child is living,wpid==[%d]\n",wpid);
	}
}



int main(int argc,char* argv[])
{
	int i = 0;
	for( i;i<3;i++)
	{
		//创建子进程
		//pid_t fork(void);
		pid_t pid = fork();
		if(pid<0)//fork失败的情况
		{
			perror("fork error");
			return -1;
		}
		else if(pid > 0)
		{
			printf("father,pid = [%d],ppid = [%d]\n",getpid(),getppid());
		}
		else if(pid == 0)
		{
			printf("child,pid = [%d],ppid = [%d]\n",getpid(),getppid());
			break;
		}
	}
	if(i==0)
	{
		printf("[%d]--[%d]:child\n",i,getpid());
		sleep(1);
	}
	if(i==1)
	{
		printf("[%d]--[%d]:child\n",i,getpid());
		sleep(2);
	}
	if(i==2)
	{
		printf("[%d]--[%d]:child\n",i,getpid());
		sleep(3);
	}	
	if(i==3)
	{
	//	printf("[%d]--[%d]:parent\n",i,getpid());
		//注册SIGCHLD信号处理函数
		struct sigaction act;
		act.sa_handler = waitchild;
		sigemptyset(&act.sa_mask);
		act.sa_flags = 0;
		sigaction(SIGCHLD,&act,NULL);
		while(1)
		{
			sleep(1);
		}
	}	
	sleep(10);
	return 0;
}
